#!/bin/bash

###############################################################################
# 军事数据加工平台 - 自动备份脚本
# 
# 功能：
# 1. 备份 MySQL 数据库
# 2. 备份上传文件（uploads 目录）
# 3. 自动清理 7 天前的备份
#
# 使用方法：
# 1. chmod +x backup.sh
# 2. 手动执行: ./backup.sh
# 3. 定时执行: 添加到 crontab
#    crontab -e
#    0 2 * * * /var/www/janes/backup.sh >> /var/log/janes_backup.log 2>&1
###############################################################################

set -e

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 配置项（请根据实际情况修改）
DB_HOST="localhost"
DB_PORT="3306"
DB_USER="root"
DB_PASSWORD="your_password"  # 注意：生产环境建议使用更安全的方式存储密码
DB_NAME="janes_production"

PROJECT_DIR="/var/www/janes"
BACKUP_DIR="/var/backups/janes"
UPLOADS_DIR="$PROJECT_DIR/uploads"

# 保留天数
KEEP_DAYS=7

# 当前时间
DATE=$(date +%Y%m%d_%H%M%S)
DATE_DISPLAY=$(date '+%Y-%m-%d %H:%M:%S')

# 创建备份目录
mkdir -p $BACKUP_DIR

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

echo "======================================"
echo "军事数据加工平台 - 备份任务"
echo "开始时间: $DATE_DISPLAY"
echo "======================================"

# 1. 备份数据库
print_info "开始备份数据库..."
DB_BACKUP_FILE="$BACKUP_DIR/db_${DB_NAME}_${DATE}.sql"

if mysqldump -h $DB_HOST -P $DB_PORT -u $DB_USER -p"$DB_PASSWORD" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    $DB_NAME > $DB_BACKUP_FILE 2>/dev/null; then
    
    # 压缩备份文件
    gzip $DB_BACKUP_FILE
    DB_SIZE=$(du -h "${DB_BACKUP_FILE}.gz" | cut -f1)
    print_success "数据库备份完成: ${DB_BACKUP_FILE}.gz (${DB_SIZE})"
else
    print_error "数据库备份失败"
    exit 1
fi

# 2. 备份上传文件
print_info "开始备份上传文件..."
UPLOADS_BACKUP_FILE="$BACKUP_DIR/uploads_${DATE}.tar.gz"

if [ -d "$UPLOADS_DIR" ]; then
    tar -czf $UPLOADS_BACKUP_FILE -C $PROJECT_DIR uploads 2>/dev/null
    UPLOADS_SIZE=$(du -h $UPLOADS_BACKUP_FILE | cut -f1)
    print_success "上传文件备份完成: $UPLOADS_BACKUP_FILE ($UPLOADS_SIZE)"
else
    print_error "上传目录不存在: $UPLOADS_DIR"
fi

# 3. 备份配置文件（可选）
print_info "备份配置文件..."
CONFIG_BACKUP_FILE="$BACKUP_DIR/config_${DATE}.tar.gz"

cd $PROJECT_DIR
tar -czf $CONFIG_BACKUP_FILE \
    .env \
    ecosystem.config.js \
    package.json \
    2>/dev/null || true

if [ -f "$CONFIG_BACKUP_FILE" ]; then
    CONFIG_SIZE=$(du -h $CONFIG_BACKUP_FILE | cut -f1)
    print_success "配置文件备份完成: $CONFIG_BACKUP_FILE ($CONFIG_SIZE)"
fi

# 4. 清理旧备份
print_info "清理 ${KEEP_DAYS} 天前的备份..."
DELETED_COUNT=0

# 删除旧的数据库备份
DELETED=$(find $BACKUP_DIR -name "db_*.sql.gz" -mtime +${KEEP_DAYS} -delete -print | wc -l)
DELETED_COUNT=$((DELETED_COUNT + DELETED))

# 删除旧的文件备份
DELETED=$(find $BACKUP_DIR -name "uploads_*.tar.gz" -mtime +${KEEP_DAYS} -delete -print | wc -l)
DELETED_COUNT=$((DELETED_COUNT + DELETED))

# 删除旧的配置备份
DELETED=$(find $BACKUP_DIR -name "config_*.tar.gz" -mtime +${KEEP_DAYS} -delete -print | wc -l)
DELETED_COUNT=$((DELETED_COUNT + DELETED))

print_success "已删除 $DELETED_COUNT 个旧备份文件"

# 5. 显示备份统计
echo ""
echo "======================================"
echo "备份统计"
echo "======================================"
echo "备份位置: $BACKUP_DIR"
echo "当前备份数量:"
echo "  - 数据库备份: $(ls -1 $BACKUP_DIR/db_*.sql.gz 2>/dev/null | wc -l) 个"
echo "  - 文件备份: $(ls -1 $BACKUP_DIR/uploads_*.tar.gz 2>/dev/null | wc -l) 个"
echo "  - 配置备份: $(ls -1 $BACKUP_DIR/config_*.tar.gz 2>/dev/null | wc -l) 个"

TOTAL_SIZE=$(du -sh $BACKUP_DIR | cut -f1)
echo "总大小: $TOTAL_SIZE"

# 6. 备份到远程服务器（可选）
# 如果需要将备份同步到远程服务器，取消下面的注释
# REMOTE_USER="backup_user"
# REMOTE_HOST="backup.example.com"
# REMOTE_DIR="/backups/janes"
# 
# print_info "同步备份到远程服务器..."
# rsync -avz --delete $BACKUP_DIR/ ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/
# if [ $? -eq 0 ]; then
#     print_success "远程同步完成"
# else
#     print_error "远程同步失败"
# fi

END_DATE=$(date '+%Y-%m-%d %H:%M:%S')
echo ""
echo "======================================"
echo "备份任务完成"
echo "结束时间: $END_DATE"
echo "======================================"

exit 0

